<?php
/**
* M:M model for holding role->privilege maps.
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/
class RolePrivilegesModel extends ScribbleModel {

	const RES_ALLOW = 'allow';
	const RES_DENY = 'deny';
	const RES_INHERIT = 'inherit';

	public function allow($priv) {
		if($this->pallow!=='*') {
			$this->pallow .= $this->pallow==='' ? $priv : ",{$priv}";
		}
		$this->pdeny = implode(",", array_diff(explode(",", $this->pdeny), array($priv)));
	}

	public function deny($priv) {
		if($this->pdeny!=='*') {
			$this->pdeny .= $this->pdeny==='' ? $priv : ",{$priv}";
		}
		$this->pallow = implode(",", array_diff(explode(",", $this->pallow), array($priv)));
	}

	/**
	* Resolves whether the privilege is allowed, denied, or inherited. One of the
	* three RolePrivilegesModel::RES_* constants is returned.
	*
	* @param string Privilege id
	* @return string
	*/
	public function resolvePrivilege($priv) {
		return $this->pallow==='*' || in_array($priv, explode(",", $this->pallow), TRUE) ? self::RES_ALLOW : (
			in_array($priv, explode(",", $this->pdeny), TRUE) ? self::RES_DENY : self::RES_INHERIT
		);
	}
}
?>